<template>
  <div class="academic-warning">
    <!-- 学生视图 -->
    <div v-if="role === 'STUDENT'">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>我的学业预警</span>
          </div>
        </template>
        
        <el-empty v-if="warnings.length === 0" description="暂无学业预警信息" />
        
        <el-table v-else :data="warnings" style="width: 100%">
          <el-table-column prop="courseName" label="课程名称" width="180" />
          <el-table-column prop="teacherName" label="任课教师" width="120" />
          <el-table-column prop="semester" label="学期" width="120" />
          <el-table-column prop="courseCredit" label="学分" width="80" />
          <el-table-column prop="warningDate" label="预警日期" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.warningDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'ACTIVE' ? 'danger' : 'success'">
                {{ scope.row.status === 'ACTIVE' ? '未解决' : '已解决' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="预警说明" min-width="200" />
          <el-table-column label="补考申请" width="180">
            <template #default="scope">
              <template v-if="scope.row.status === 'ACTIVE'">
                <el-button v-if="!scope.row.makeupStatus || scope.row.makeupStatus === '未申请'" type="primary" size="small" @click="applyMakeupExam(scope.row)">
                  申请补考
                </el-button>
                <span v-else-if="scope.row.makeupStatus === '待审核'" style="color:#e6a23c">已申请，待审核</span>
                <span v-else-if="scope.row.makeupStatus === '已批准'" style="color:#409eff">已批准，等待补考</span>
                <span v-else-if="scope.row.makeupStatus === '补考通过'" style="color:#67c23a">补考通过，分数：{{ scope.row.makeupScore }}</span>
                <span v-else-if="scope.row.makeupStatus === '补考未通过'" style="color:#f56c6c">补考未通过，分数：{{ scope.row.makeupScore }}</span>
              </template>
              <span v-else>--</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <!-- 教师视图 -->
    <div v-else-if="role === 'TEACHER'">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>课程学业预警统计</span>
            <el-button type="primary" size="small" @click="fetchTeacherWarningStats">刷新</el-button>
          </div>
        </template>
        
        <el-empty v-if="courseWarningStats.length === 0" description="暂无学业预警信息" />
        
        <el-table v-else :data="courseWarningStats" style="width: 100%">
          <el-table-column prop="courseName" label="课程名称" width="200" />
          <el-table-column prop="semester" label="学期" width="120" />
          <el-table-column prop="credits" label="学分" width="80" />
          <el-table-column prop="warningCount" label="预警人数" width="100" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="showWarningStudents(scope.row.courseId)"
              >
                查看名单
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 学生名单对话框 -->
      <el-dialog v-model="studentListVisible" title="预警学生名单" width="1000px">
        <el-table :data="warningStudents" style="width: 100%">
          <el-table-column prop="studentNumber" label="学号" width="120" />
          <el-table-column prop="studentName" label="姓名" width="120" />
          <el-table-column prop="warningDate" label="预警日期" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.warningDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'ACTIVE' ? 'danger' : 'success'">
                {{ scope.row.status === 'ACTIVE' ? '未解决' : '已解决' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="预警说明" />
          <el-table-column label="补考申请" width="180">
            <template #default="scope">
              <template v-if="scope.row.status === 'ACTIVE'">
                <span v-if="!scope.row.makeupStatus || scope.row.makeupStatus === '未申请'" style="color:#909399">未申请</span>
                <span v-else-if="scope.row.makeupStatus === '待审核'" style="color:#e6a23c">已申请，待审核</span>
                <span v-else-if="scope.row.makeupStatus === '已批准'" style="color:#409eff">已批准，等待补考</span>
                <span v-else-if="scope.row.makeupStatus === '补考通过'" style="color:#67c23a">补考通过，分数：{{ scope.row.makeupScore }}</span>
                <span v-else-if="scope.row.makeupStatus === '补考未通过'" style="color:#f56c6c">补考未通过，分数：{{ scope.row.makeupScore }}</span>
              </template>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button v-if="scope.row.makeupStatus === '待审核' || scope.row.makeupStatus === '已批准'" type="primary" size="small" @click="redirectToMakeupExam(scope.row)">
                前往补考管理
              </el-button>
              <span v-else>--</span>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
    
    <!-- 管理员视图 -->
    <div v-else-if="role === 'ADMIN'">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>全校学业预警统计</span>
            <div class="header-controls">
              <el-button type="primary" size="small" @click="fetchAllWarningStats">刷新</el-button>
            </div>
          </div>
        </template>
        
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程名称"
          style="width: 300px; margin-bottom: 20px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><search /></el-icon>
          </template>
        </el-input>
        
        <el-empty v-if="filteredWarningStats.length === 0" description="暂无学业预警信息" />
        
        <el-table v-else :data="filteredWarningStats" style="width: 100%">
          <el-table-column prop="courseName" label="课程名称" width="200" />
          <el-table-column prop="teacherName" label="任课教师" width="120" />
          <el-table-column prop="semester" label="学期" width="120" />
          <el-table-column prop="credits" label="学分" width="80" />
          <el-table-column prop="warningCount" label="预警人数" width="100" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="showWarningStudents(scope.row.courseId)"
              >
                查看名单
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 管理员视图的学生名单对话框 -->
      <el-dialog v-model="studentListVisible" title="预警学生名单" width="1000px">
        <el-table :data="warningStudents" style="width: 100%">
          <el-table-column prop="studentNumber" label="学号" width="120" />
          <el-table-column prop="studentName" label="姓名" width="120" />
          <el-table-column prop="warningDate" label="预警日期" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.warningDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'ACTIVE' ? 'danger' : 'success'">
                {{ scope.row.status === 'ACTIVE' ? '未解决' : '已解决' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="预警说明" />
          <el-table-column label="补考申请" width="180">
            <template #default="scope">
              <template v-if="scope.row.status === 'ACTIVE'">
                <span v-if="!scope.row.makeupStatus || scope.row.makeupStatus === '未申请'" style="color:#909399">未申请</span>
                <span v-else-if="scope.row.makeupStatus === '待审核'" style="color:#e6a23c">已申请，待审核</span>
                <span v-else-if="scope.row.makeupStatus === '已批准'" style="color:#409eff">已批准，等待补考</span>
                <span v-else-if="scope.row.makeupStatus === '补考通过'" style="color:#67c23a">补考通过，分数：{{ scope.row.makeupScore }}</span>
                <span v-else-if="scope.row.makeupStatus === '补考未通过'" style="color:#f56c6c">补考未通过，分数：{{ scope.row.makeupScore }}</span>
              </template>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button v-if="scope.row.makeupStatus === '待审核' || scope.row.makeupStatus === '已批准'" type="primary" size="small" @click="redirectToMakeupExam(scope.row)">
                前往补考管理
              </el-button>
              <span v-else>--</span>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

export default {
  name: 'AcademicWarning',
  components: {
    Search
  },
  props: {
    studentId: {
      type: [Number, String],
      required: false
    },
    role: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const warnings = ref([])
    const courseWarningStats = ref([])
    const allWarningStats = ref([])
    const warningStudents = ref([])
    const studentListVisible = ref(false)
    const searchQuery = ref('')
    const router = useRouter()
    
    // 过滤后的预警统计
    const filteredWarningStats = computed(() => {
      if (!searchQuery.value) {
        return allWarningStats.value
      }
      
      const query = searchQuery.value.toLowerCase()
      return allWarningStats.value.filter(item => 
        item.courseName.toLowerCase().includes(query) ||
        (item.teacherName && item.teacherName.toLowerCase().includes(query))
      )
    })
    
    // 获取学生的学业预警
    const fetchStudentWarnings = async () => {
      try {
        const response = await axios.get(`/api/users/me/academic-warnings?studentId=${props.studentId}`);
        warnings.value = response.data;
        // 查询补考申请并合并状态
        const makeupRes = await axios.get(`/api/makeup-exam/student?studentId=${props.studentId}`);
        const makeupMap = {};
        (makeupRes.data || []).forEach(app => {
          makeupMap[app.courseId] = app;
        });
        
        // 过滤掉补考通过的学业预警
        warnings.value = warnings.value
          .filter(w => {
            const makeup = makeupMap[w.courseId];
            // 如果补考通过，则过滤掉该预警
            if (makeup && makeup.status === '补考通过') {
              console.log(`过滤掉补考通过的学业预警: 学生ID=${w.studentId}, 课程ID=${w.courseId}`);
              return false;
            }
            return true;
          })
          .map(w => {
            const makeup = makeupMap[w.courseId];
            if (makeup) {
              return {
                ...w,
                makeupStatus: makeup.status,
                makeupScore: makeup.makeupScore
              };
            }
            return w;
          });
          
        console.log('处理后的学业预警:', warnings.value);
      } catch (error) {
        ElMessage.error('获取学业预警失败');
      }
    }
    
    // 获取教师课程的学业预警统计
    const fetchTeacherWarningStats = async () => {
      try {
        const response = await axios.get(`/api/teacher/academic-warnings/stats?teacherId=${props.studentId}`)
        courseWarningStats.value = response.data
      } catch (error) {
        console.error('获取课程学业预警统计失败:', error)
        ElMessage.error('获取课程学业预警统计失败')
      }
    }
    
    // 获取所有课程的学业预警统计
    const fetchAllWarningStats = async () => {
      try {
        const response = await axios.get('/api/admin/academic-warnings/stats')
        allWarningStats.value = response.data
      } catch (error) {
        console.error('获取所有课程学业预警统计失败:', error)
        ElMessage.error('获取所有课程学业预警统计失败')
      }
    }
    
    // 查看课程的预警学生名单
    const showWarningStudents = async (courseId) => {
      try {
        console.log(`正在获取课程 ${courseId} 的预警学生名单`);
        const response = await axios.get(`/api/academic-warnings/course/${courseId}`);
        console.log(`获取课程 ${courseId} 的预警学生名单成功:`, response.data);
        
        // 过滤掉补考通过的学业预警
        warningStudents.value = response.data.filter(student => {
          if (student.makeupStatus === '补考通过') {
            console.log(`过滤掉补考通过的学生预警: 学生=${student.studentName}, 课程ID=${courseId}`);
            return false;
          }
          return true;
        });
        
        console.log('过滤后的预警学生名单:', warningStudents.value);
        studentListVisible.value = true;
      } catch (error) {
        console.error(`获取预警学生名单失败:`, error);
        console.error(`请求URL: /api/academic-warnings/course/${courseId}`);
        console.error(`错误详情:`, error.response?.data || error.message);
        ElMessage.error('获取预警学生名单失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    }
    
    // 搜索处理
    const handleSearch = () => {
      // 使用计算属性自动过滤
    }
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const d = new Date(dateStr);
      return `${d.getFullYear()}/${d.getMonth()+1}/${d.getDate()} ${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`;
    }
    
    // 申请补考
    const applyMakeupExam = async (warning) => {
      try {
        await ElMessageBox.confirm(`确定要为课程"${warning.courseName}"申请补考吗？`, '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 确保courseId有值并记录日志
        if (!warning.courseId) {
          console.error('补考申请失败: 课程ID为空', warning);
          ElMessage.error('补考申请失败: 课程ID不能为空');
          return;
        }
        
        console.log('提交补考申请, 参数:', {
          studentId: warning.studentId,
          courseId: warning.courseId,
          applyTime: new Date()
        });
        
        // 使用POST JSON格式，确保课程ID正确传递
        const response = await axios.post('/api/makeup-exam/apply', {
          studentId: warning.studentId,
          courseId: warning.courseId,
          applyTime: new Date()
        });
        
        console.log('补考申请提交响应:', response.data);
        
        if (response.data) {
          ElMessage.success('补考申请已提交');
          // 刷新学业预警状态
          if (props.role === 'STUDENT') {
            await fetchStudentWarnings();
          } else if (props.role === 'ADMIN') {
            // 如果在管理员视图中，刷新当前查看的学生列表
            if (studentListVisible.value) {
              await showWarningStudents(warning.courseId);
            }
          }
        } else {
          ElMessage.error('补考申请失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('补考申请失败:', error);
          console.error('错误详情:', error.response?.data || error.message);
          ElMessage.error('补考申请失败: ' + (error.response?.data?.message || error.message || '未知错误'));
        }
      }
    }
    
    // 跳转到补考管理页面
    const redirectToMakeupExam = (student) => {
      console.log('正在跳转到补考管理页面，参数:', {
        studentId: student.studentId,
        courseId: student.courseId
      });
      
      // 确保studentId和courseId有效
      if (!student.studentId) {
        console.error('跳转失败：studentId为空');
        ElMessage.error('跳转失败：学生ID为空');
        return;
      }
      
      // 使用replace而不是push，避免历史记录堆积
      router.replace({
        path: '/academic',
        query: { 
          tab: 'makeup-exam',
          studentId: student.studentId
          // 不传递courseId，避免undefined问题
        }
      });
      
      // 强制刷新当前页面以确保导航生效
      window.location.href = `/academic?tab=makeup-exam&studentId=${student.studentId}`;
      
      // 通知用户
      ElMessage({
        message: '正在跳转到补考管理页面，请稍候...',
        type: 'success'
      });
    }
    
    let timer = null
    onMounted(() => {
      if (props.role === 'STUDENT') {
        fetchStudentWarnings()
      } else if (props.role === 'TEACHER') {
        fetchTeacherWarningStats()
      } else if (props.role === 'ADMIN') {
        fetchAllWarningStats()
      }
      // 只定时调用实际存在的刷新方法
      if (props.role === 'STUDENT' && typeof fetchStudentWarnings === 'function') {
        timer = setInterval(() => {
          fetchStudentWarnings()
        }, 5000)
      } else if (props.role === 'TEACHER' && typeof fetchTeacherWarningStats === 'function') {
        timer = setInterval(() => {
          fetchTeacherWarningStats()
        }, 5000)
      } else if (props.role === 'ADMIN' && typeof fetchAllWarningStats === 'function') {
        timer = setInterval(() => {
          fetchAllWarningStats()
        }, 5000)
      }
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })
    
    return {
      warnings,
      courseWarningStats,
      allWarningStats,
      filteredWarningStats,
      warningStudents,
      studentListVisible,
      searchQuery,
      formatDate,
      fetchStudentWarnings,
      fetchTeacherWarningStats,
      fetchAllWarningStats,
      showWarningStudents,
      handleSearch,
      applyMakeupExam,
      redirectToMakeupExam
    }
  }
}
</script>

<style scoped>
.academic-warning {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
}
</style>